package cn.smile.controller.admin;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.smile.bean.CodeMsg;
import cn.smile.bean.PageBean;
import cn.smile.bean.Result;
import cn.smile.entity.admin.User;
import cn.smile.service.admin.OperaterLogService;
import cn.smile.service.admin.RoleService;
import cn.smile.service.admin.UserService;
import cn.smile.util.ValidateEntityUtil;

import javax.annotation.Resource;

/**
 * 后台用户管理控制器
 */
@RequestMapping("/admin/user")
@Controller
public class UserController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private OperaterLogService operaterLogService;

    /**
     * 用户列表页面
     */
    @RequestMapping(value = "/list")
    public String list(Model model, User user, PageBean<User> pageBean) {
        model.addAttribute("title", "用户列表");
        model.addAttribute("username", user.getUsername());
        model.addAttribute("pageBean", userService.findList(user, pageBean));
        return "admin/user/list";
    }

    /**
     * 新增用户页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(Model model) {
        model.addAttribute("roles", roleService.findAll());
        return "admin/user/add";
    }

    /**
     * 用户添加表单提交处理
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> add(User user) {
        //用统一验证实体方法验证是否合法
        Result<Boolean> validate = getBooleanResult(user);
        if (validate != null) return validate;
        //判断用户名是否存在
        if (userService.isExistUsername(user.getUsername(), 0L)) {
            return Result.error(CodeMsg.ADMIN_USERNAME_EXIST);
        }
        //到这说明一切符合条件，进行数据库新增
        if (userService.save(user) == null) {
            return Result.error(CodeMsg.ADMIN_USE_ADD_ERROR);
        }
        operaterLogService.add("添加用户，用户名：" + user.getUsername());
        return Result.success(true);
    }

    /**
     * 用户编辑页面
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, @RequestParam(name = "id") Long id) {
        model.addAttribute("roles", roleService.findAll());
        model.addAttribute("user", userService.find(id));
        return "admin/user/edit";
    }

    /**
     * 编辑用户信息表单提交处理
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> edit(User user) {
        //用统一验证实体方法验证是否合法
        Result<Boolean> validate = getBooleanResult(user);
        if (validate != null) return validate;
        if (user.getId() == null || user.getId() <= 0) {
            return Result.error(CodeMsg.ADMIN_USE_NO_EXIST);
        }
        if (userService.isExistUsername(user.getUsername(), user.getId())) {
            return Result.error(CodeMsg.ADMIN_USERNAME_EXIST);
        }
        //到这说明一切符合条件，进行数据库保存
        User findById = userService.find(user.getId());
        //讲提交的用户信息指定字段复制到已存在的user对象中,该方法会覆盖新字段内容
        BeanUtils.copyProperties(user, findById, "id", "createTime", "updateTime");
        if (userService.save(findById) == null) {
            return Result.error(CodeMsg.ADMIN_USE_EDIT_ERROR);
        }
        operaterLogService.add("编辑用户，用户名：" + user.getUsername());
        return Result.success(true);
    }

    /**
     * 删除用户
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result<Boolean> delete(@RequestParam(name = "id") Long id) {
        try {
            userService.delete(id);
        } catch (Exception e) {
            return Result.error(CodeMsg.ADMIN_USE_DELETE_ERROR);
        }
        operaterLogService.add("添加用户，用户ID：" + id);
        return Result.success(true);
    }

    private static Result<Boolean> getBooleanResult(User user) {
        CodeMsg validate = ValidateEntityUtil.validate(user);
        if (validate.getCode() != CodeMsg.SUCCESS.getCode()) {
            return Result.error(validate);
        }
        if (user.getRole() == null || user.getRole().getId() == null) {
            return Result.error(CodeMsg.ADMIN_USER_ROLE_EMPTY);
        }
        return null;
    }
}
